package com.apache.client.common;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Xstream工具类
 *
 * @author dyhou
 */
public class XmlUtil {

    private XmlUtil() {
        //XmlUtil
    }

    private static final String xmlStart = "<xml-body>\n<Head></Head>\n<Body>\n";

    private static final String xmlEnd = "\n</Body>\n</xml-body>";

    private static XStream xstream;

    static {
        xstream = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
    }

    private static String xmlHead = "<?xml version='1.0' encoding='UTF-8'?>\n";

    /**
     * java 转换成xml
     *
     * @param obj 对象实例
     * @return String xml字符串
     */
    public static String toXml(Object obj) {
        ////如果没有这句，xml中的根元素会是<包.类名>；或者说：注解根本就没生效，所以的元素名就是类的属性
        xstream.processAnnotations(obj.getClass()); //通过注解方式的，一定要有这句话
        return xmlHead + xstream.toXML(obj);
    }

    /**
     * 将传入xml文本转换成Java对象
     *
     * @param xmlStr
     * @param cls xml对应的class类
     * @return T   xml对应的class类的实例对象
     * 调用的方法实例：PersonBean person=XmlUtil.toBean(xmlStr, PersonBean.class);
     */
    public static <T> T toBean(String xmlStr, Class<T> cls) {
        xmlStr = xmlStr.trim();
        xmlStr = xmlStr.replaceAll(xmlStart, "");
        xmlStr = xmlStr.replaceAll(xmlEnd, "");
        xstream.alias(cls.getSimpleName(), cls);
        xstream.processAnnotations(cls);
        T obj = (T) xstream.fromXML(xmlStr);
        return obj;
    }

    /**
     * 输出客户端信息
     *
     * @param xml
     * @param response
     */
    public static void outputXml(String xml, HttpServletResponse response) {
        try {
            response.setContentType("text/xml; charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print(xml);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
